<?php

class TemplateGenerator
{
  function isValidZip($file,$name)
  {
    $error = 0;
    $zip = new ZipArchive();
    if ($zip->open($file) === TRUE)
    {
      $zip->close();
    }
    else
      $error++;
    return ($error == 0);
  }
  
  function createTemplate($file,$name, $user_template_dir)
  {
    $error = 0;
    $template_dir = $user_template_dir;
    
    $dir_name = preg_replace("/\\.[^.\\s]{3,4}$/", "", $name);
    
    $destination_dir = $template_dir.$dir_name;
    echo $destination_dir;

    if (file_exists($destination_dir))
    {
      //TODO: error handling
      return;
    }

    if ($this->isValidZip($file, $name))
    {
      mkdir($template_dir.$dir_name);
      chmod($template_dir.$dir_name, 0777);
      $zip = new ZipArchive();
      $zip->open($file);
      $zip->extractTo($template_dir.$dir_name);
      // Good idea? (needed for testing)
      $zip->close();
    }
    // TODO: Error handling
  }
}
?>